/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package knowledgebase.dao;

import java.sql.SQLException;
import java.util.List;
import knowledgebase.model.Role;
import knowledgebase.model.RoleGlobalPermission;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author eugene
 */
@Repository("roleDAO")
@Transactional
public class RoleDAOImpl implements RoleDAO {
    
    @Autowired
    private PermissionDAO permissionDAO;

    private HibernateTemplate hibernateTemplate;
    Log log = LogFactory.getLog(getClass());

    @Autowired
    public void setSessionFactory(SessionFactory sessionFactory) {
        hibernateTemplate = new HibernateTemplate(sessionFactory);
    }

    @Override
    public List<Role> getAllRoles() {
        return (List<Role>) hibernateTemplate.find("from Role");
    }

    @Override
    public void addOrUpdateRole(Role role) {
        hibernateTemplate.saveOrUpdate(role);
    }

    @Override
    public void removeRole(long roleId) {
        permissionDAO.removeAllRoleGlobalPermissions(roleId);
        Role role = hibernateTemplate.load(Role.class, roleId);
        hibernateTemplate.delete(role);
    }
    
    @Override
    public Role getRoleByName(String roleName) {
        List<Role> roles = hibernateTemplate.find("from Role r where r.name = ?", roleName);
        return !roles.isEmpty() ? roles.get(0) : new Role();
    }
    
    @Override
    public List<Role> searchRoles(String name, int startIndex, int size){
        log.debug("searchRoles("+name+", "+startIndex+", "+size+")");
        if(name==null) name="";
        
        List<Role> roles = hibernateTemplate.find("from Role where name like ?", "ROLE_"+name+"%");
        
        if(roles.size()>startIndex+size){
            return roles.subList(startIndex, startIndex+size+1);
        } else {
            return roles.subList(startIndex, roles.size());
        }
    }
    
    @Override
    public long getUserCount() {
        return hibernateTemplate.execute(new HibernateCallback<Long>() {

            @Override
            public Long doInHibernate(Session session) throws HibernateException, SQLException {
                Criteria criteria = session.createCriteria(Role.class);
                criteria.setProjection(Projections.rowCount());
                return (Long) criteria.uniqueResult();
            }
        });
    }
}